//
//  SearchViewController.m
//  A_Comic
//
//  Created by sos on 16/1/23.
//  Copyright © 2016年 sos. All rights reserved.
//

#import "SearchViewController.h"
#import <AFNetworking.h>
#import "WMESongListModel.h"
#import "WMEPlayerViewController.h"
#import "WMEPlayerModel.h"
#import "NetwrokHandler.h"
#import "WMESearchTableViewCell.h"
//#import "NSArray+ShareInstance.h"
//#import "WMEFirstPageInformationVC.h"
//#import "SearchModel.h"
@interface SearchViewController ()<UISearchBarDelegate, UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UISearchBar *searchBar;
@property (nonatomic,strong) NSMutableArray *dataArr;
@property (nonatomic,strong) WMESongListModel *str;
@property (nonatomic,strong) UILabel *label;
@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArr = [NSMutableArray array];
//    [self.navigationController setNavigationBarHidden:YES animated:YES];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    //创建
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height-64) style:UITableViewStylePlain];
    //签订代理人
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    //注册
    [self.tableView registerClass:[WMESearchTableViewCell class] forCellReuseIdentifier:@"cell"];
    self.tableView.hidden = YES;
    
    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, 44)];
    self.searchBar.placeholder = @"请输入要搜索的内容";

//    searchBar.showsCancelButton = YES;
    self.searchBar.delegate = self;
    
    self.searchBar.clearsContextBeforeDrawing = YES;
//    self.tableView.tableHeaderView = searchBar;
//    [self.view addSubview:self.searchBar];
    
    self.navigationItem.titleView = _searchBar;
    
//        [self data];

    
    
    
    
}
-(void)data
{
//    NSMutableArray *sousuoDataArr = [NSArray shareDefuld];
    
//    NSLog(@"~~~~~~~~~~%@",sousuoDataArr);
//    for (NSDictionary *dic in sousuoDataArr) {
//    self.dataArr = [HomePageModel modelHandlerWithArray:sousuoDataArr];
//    self.dataArr = sousuoDataArr;
//    self.dataArr = [HomePageModel modelHandlerWithArray:sousuoDataArr];


}


//协议方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WMESearchTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    WMESongListModel *m = self.dataArr[indexPath.row];
    //范围性关键字高亮
    NSString *data = m.title;
    [data rangeOfString:m.title];
    NSRange range = [data rangeOfString:self.searchBar.text];
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]initWithString:m.title];

    [attr setAttributes:@{NSForegroundColorAttributeName: [UIColor redColor]} range:range];
    
    NSString *name = m.author;
    [name rangeOfString:m.author];
    NSRange fw = [name rangeOfString:self.searchBar.text];
    NSMutableAttributedString *authorName = [[NSMutableAttributedString alloc] initWithString:m.author];
    [authorName setAttributes:@{NSForegroundColorAttributeName: [UIColor redColor]} range:fw];
    
    cell.songName.attributedText = attr;
    cell.author.attributedText = authorName;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_dataArr.count) {
        WMESongListModel *model = _dataArr[indexPath.row];
        NSString *str = [@"http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.song.getInfos&ts=1461321078&songid=7330118&nw=2&l2p=218.9&lpb=320000&ext=MP3&format=json&from=ios&usup=1&lebo=0&aac=0&ucf=4&vid=&res=1&e=qfJshuUl8FS63N7L4gV2HAP%2FtWo%2F43nPR3pY%2FvY8iAo%3D&version=5.5.6&from=ios&channel=appstore&operator=1" stringByReplacingOccurrencesOfString:@"songid=7330118" withString:[NSString stringWithFormat:@"songid=%@", model.song_id]];
        [WMEAFNetworking GETNetWithUrl:str body:nil headerFile:nil response:WMEJOSN success:^(id result) {
            WMEPlayerViewController *playerVC = [[WMEPlayerViewController alloc] init];
            NSMutableArray *arr = [NSMutableArray array];
            arr = [WMEPlayerModel modelHandlerWithArray:result[@"songurl"][@"url"]];
            playerVC.listArr = arr;
            playerVC.dic = result;
            playerVC.songArr = _dataArr;
            playerVC.index = indexPath.row;
            NSString *strURL = result[@"songinfo"][@"lrclink"];
            [NetwrokHandler GETWithURL:strURL completion:^(id result) {
                NSLog(@"result");
                playerVC.str = result;
                [self presentViewController:playerVC animated:YES completion:^{
                    NSLog(@"模态成功");
                }];
            }];
        } failure:^(NSError *error) {
            NSLog(@"网络请求错误");
        }];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65;
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    //获得searchbar中用户输入的内容
    NSString *str = self.searchBar.text;
    [_label removeFromSuperview];
    UILabel *huo = [self.view viewWithTag:5002];
    [huo removeFromSuperview];
//    NSString *url = [strOne stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //根据转码后的字符串 拼接网址 进行网络请求
    NSString *urlStr = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:str]];

    // 拼接
    NSString *url =[@"http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.merge&query=%E5%91%A8%E6%9D%B0%E4%BC%A6&page_size=50&page_no=1&type=-1&format=json&from=ios&version=5.6.0&from=ios&channel=appstore&operator=1" stringByReplacingOccurrencesOfString:@"query=%E5%91%A8%E6%9D%B0%E4%BC%A6" withString:[NSString stringWithFormat:@"query=%@", urlStr]];
    NSLog(@"%@", url);
    
    AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
    [data GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        NSLog(@"%@", responseObject);
        
        NSArray *arr = responseObject[@"result"][@"song_info"][@"song_list"];
        self.dataArr = [WMESongListModel modelHandlerWithArray:arr];
        [_tableView reloadData];
        if (_dataArr.count == 0) {
            UILabel *kong = [[UILabel alloc] initWithFrame:self.view.bounds];
            kong.backgroundColor = [UIColor whiteColor];
            kong.text = @"搜不到";
            kong.textAlignment = NSTextAlignmentCenter;
            kong.tag = 5002;
            [self.view addSubview:kong];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
    

    self.tableView.hidden = NO;
    [self.tableView reloadData];
    [self.searchBar resignFirstResponder];
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.dataArr removeAllObjects];
    self.searchBar.text = nil;
    [self.tableView reloadData];
    if (![_searchBar.text length]) {
        self.label = [[UILabel alloc] initWithFrame:self.view.frame];
        _label.text = @"请,你还未输入哦";
        _label.backgroundColor = [UIColor whiteColor];
        _label.textAlignment = NSTextAlignmentCenter;
        [self.view addSubview:_label];
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
